package com.summo.demo.config.format;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;

/**
 * <p>Description:指定FastJson的MessageConverter，解决双引号""被转移成&quot</p>
 */
@Configuration
public class FormatConvertersConfig {
    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        List<MediaType> list = new ArrayList<>();
        list.add(MediaType.APPLICATION_JSON);
        FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        config.setCharset(StandardCharsets.UTF_8);
        //设置允许返回为null的属性
        config.setSerializerFeatures(SerializerFeature.PrettyFormat);
        fastJsonConverter.setFastJsonConfig(config);
        fastJsonConverter.setSupportedMediaTypes(list);
        StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
        stringHttpMessageConverter.setSupportedMediaTypes(list);
        //此处需要先放入字符串解析器，再放入fastjson解析器，否则字符串返回会自动带上双引号
        return new HttpMessageConverters(stringHttpMessageConverter, fastJsonConverter);
    }
}
